package elec315.chatroom.client.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import elec315.chatroom.client.ClientRequestHandler;

public class ConsoleUI implements Runnable, UIBuilder {

	private static final Log logger = LogFactory.getLog(ConsoleUI.class);

	private static final String COMMAND_GET_USER_LIST = "/who";
	private static final String COMMAND_QUIT = "/quit";

	private final ClientRequestHandler clientRequestHandler;

	public ConsoleUI(ClientRequestHandler clientRequestHandler) {
		super();
		this.clientRequestHandler = clientRequestHandler;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		logger.debug("ConsoleUI is started.");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String userId = null;
		String str = null;
		while (true) {
			System.out.println("What's your name?");
			try {
				str = in.readLine();
			} catch (IOException ex) {
				logger.error(ex, ex);
			}
			if (StringUtils.isNotBlank(str)) {
				userId = str;
				clientRequestHandler.login(userId);
				break;
			}
		}
		System.out.println("Press \"" + COMMAND_GET_USER_LIST + "\" to show user list.");
		System.out.println("Press \"" + COMMAND_QUIT + "\" to quit.");
		while (true) {
			try {
				str = in.readLine();
			} catch (IOException ex) {
				logger.error(ex, ex);
			}
			if (COMMAND_QUIT.equals(str)) {
				clientRequestHandler.logout(userId);
				break;
			} else if (COMMAND_GET_USER_LIST.equals(str)) {
				clientRequestHandler.getUserList();
			} else {
				clientRequestHandler.broadcast(str);
			}
		}
		System.out.println("Disconnected from server.");
		System.exit(0);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see elec315.chatroom.client.ui.UIBuilder#printMessage(java.lang.String)
	 */
	@Override
	public void printMessage(String message) {
		System.out.println(message);
	}

}
